package com.example.zhanghao.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.example.zhanghao.DTO.PayDto;
import kong.unirest.Unirest;
import org.apache.commons.codec.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import static com.example.zhanghao.config.HuPiJiaoConstant.*;
import kong.unirest.HttpResponse;


@Component
public class LanTuHandler {

    private static final Logger LOG = LoggerFactory.getLogger(LanTuHandler.class);

    /**
     * 获取精确到秒的时间戳   原理 获取毫秒时间戳，因为 1秒 = 100毫秒 去除后三位 就是秒的时间戳
     * @return
     */
    public static String getSecondTimestamp(Date date){
        if (null == date) {
            return "0";
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return timestamp.substring(0,length-3);
        } else {
            return "0";
        }
    }


    public static String getHashAndTime(PayDto payDto){
        // 请求路径
        String url = "https://api.ltzf.cn/api/wxpay/h5";

        Map<String,String> options = new HashMap<>();
        // 设置版本号
        options.put("mch_id","1680848574");

        // 密钥不需要参数
        //options.put("appsecret",appsecret);

        // 订单号 具体内容自己控制 长度 32位
        options.put("out_trade_no",payDto.getTradeOrderId());

        // 价格价格 精确到分
        options.put("total_fee",payDto.getTotalFee());

        // 标题
        options.put("body",payDto.getTitle());

        // 当前时间戳 调用 刚写的方法 getSecondTimestamp
        options.put("timestamp", getSecondTimestamp(new Date()));

        // notify_url 回调地址
        options.put("notify_url",notify_url);

        String sign = createSign(options,"63f8b7f6e4c56e13d84f1696853693e6");

        // 必填 hash 签名
        options.put("sign", sign);

        if(payDto.getPayType().equals("phone")){
            options.put("return_url","http://192.168.3.131:5185/pHome/index");
        }

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : options.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        String result = sb.toString();

      String postRes = HttpUtil.post(url, result);

      return postRes;

    }

    public static String packageSign(Map < String, String > params, boolean urlEncoder) {
        // 先将参数以其参数名的字典序升序进行排序
        TreeMap< String, String > sortedParams = new TreeMap< String, String >(params);
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (Map.Entry< String, String > param: sortedParams.entrySet()) {
            String value = param.getValue();
            if (StrKit.isBlank(value)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            sb.append(param.getKey()).append("=");
            if (urlEncoder) {
                try {
                    value = urlEncode(value);
                } catch (UnsupportedEncodingException e) {}
            }
            sb.append(value);
        }
        return sb.toString();
    }

    public static String urlEncode(String src) throws UnsupportedEncodingException {
        return URLEncoder.encode(src, Charsets.UTF_8.name()).replace("+", "%20");
    }

    public static String createSign(Map < String, String > params, String partnerKey) {
        // 生成签名前先去除sign
        params.remove("sign");
        String stringA = packageSign(params, false);
        String stringSignTemp = stringA + "&key=" + partnerKey;
        return StrKit.md5(stringSignTemp).toUpperCase();
    }

}